package com.bub.pay.core.util.resp;

import com.bub.pay.core.manager.system.CurrentSystemManager;
import com.bub.pay.framework.common.base.Cause;
import com.bub.pay.framework.common.base.Module;
import com.bub.pay.framework.common.entity.model.RespObject;
import com.bub.pay.framework.common.exception.GlobalException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.validation.BindException;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;

import java.util.List;

/**
 * 返回报文
 *
 * @author recall
 * @date 2019/6/28
 */
@Slf4j
@Component
public class RespBuild {

    private static CurrentSystemManager currentSystemManager;

    public static <T> RespObject<T> build(Command<T> command) {
        T data = null;
        try {
            if (command instanceof VoidCommand) {
                ((VoidCommand) command).executable();
            } else if (command instanceof ResultCommand) {
                data = ((ResultCommand<T>) command).executable();
            }
        } catch (Exception e) {
            log.error("error", e);
            Module module = currentSystemManager.getModule();
            GlobalException ge;
            if (e instanceof MethodArgumentNotValidException) {
                MethodArgumentNotValidException methodArgumentNotValidException = (MethodArgumentNotValidException) e;
                String defaultMess = "系统异常";
                List<ObjectError> errList = methodArgumentNotValidException.getBindingResult().getAllErrors();
                if (!errList.isEmpty()) {
                    defaultMess = errList.get(0).getDefaultMessage();
                }
                ge = new GlobalException(module, (module.getSn() * GlobalException.CARRY) + Cause.params_fail.getCode(), defaultMess);
            } else if (e instanceof BindException) {
                String message = ((BindException) e).getBindingResult().getFieldError().getDefaultMessage();
                ge = new GlobalException(module, (module.getSn() * GlobalException.CARRY) + Cause.params_fail.getCode(), message);
            } else if (e instanceof IllegalArgumentException) {
                ge = new GlobalException(module, (module.getSn() * GlobalException.CARRY) + Cause.params_fail.getCode(), e.getMessage());
            } else if (e instanceof GlobalException) {
                ge = (GlobalException) e;
            } else {
                ge = new GlobalException(module, Cause.unknown, e);
            }
            return new RespObject<>(ge);
        }
        return new RespObject<>(data);
    }

    @Autowired
    public void setCurrentSystemManager(CurrentSystemManager currentSystemManager) {
        RespBuild.currentSystemManager = currentSystemManager;
    }
}

